package ext.tianma.workflow;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import wt.change2.ChangeHelper2;
import wt.change2.WTChangeActivity2;
import wt.change2.WTChangeOrder2;
import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentItem;
import wt.content.ContentRoleType;
import wt.doc.WTDocument;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.ObjectVector;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.WTReference;
import wt.fc.collections.WTArrayList;
import wt.iba.value.IBAHolder;
import wt.inf.container.WTContained;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.LifeCycleManaged;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.WTPrincipalReference;
import wt.part.WTPart;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.Iterated;
import wt.vc.VersionControlHelper;
import wt.vc.wip.WorkInProgressHelper;
import wt.vc.wip.Workable;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfExecutionObject;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfRequester;
import wt.workflow.engine.WfRequesterActivity;
import wt.workflow.engine.WfState;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WorkItem;
import wt.workflow.work.WorkflowHelper;

import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.netmarkets.workflow.NmWorkflowHelper;

import ext.com.iba.IBAUtil;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.util.IbaAttributeUtil;

public class WorkflowUtil implements RemoteAccess
{
    public static boolean VERBOSE = false;
    public static WTProperties wtProperties;
    public static String CLASSNAME = "";
    private static String configFilePath = "";
    private static String sheetName = "WFTemplate";
    static final boolean SERVER;
    private static String PROEPETIESFILE = "ext.shantuict.wfaugment.wfaugment";
 

    static
    {
        CLASSNAME = WorkflowUtil.class.getName();
        SERVER = RemoteMethodServer.ServerFlag;
        try
        {
            wtProperties = WTProperties.getLocalProperties();
            VERBOSE = wtProperties.getProperty("ext.shantuict.workflow.verbose", false);
            configFilePath = wtProperties.getProperty("ext.generic.WFTemplateGuide", "");
        }
        catch (java.io.IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

    /**
     *获取PBO相关流程的所有签审信息
     */
    public static Hashtable queryElectronicSignature(WTObject pbo) throws Exception
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".queryElectronicSignature()--object=" + pbo.getDisplayIdentity());
        Hashtable signatureInfo = new Hashtable(); 
        Timestamp modifiedTime=null;        
        Hashtable ibaValues = IBAUtil.getIBAValues((IBAHolder) pbo);
        String processOid = (String) ibaValues.get("ProcessInfo");
        if (VERBOSE)
            System.out.println("	process Oid =" + processOid);
        ReferenceFactory rf = new ReferenceFactory();
        WfProcess process = null;
        //pbo没有processInfo,查找与pbo关联的流程	
        if (processOid==null||processOid.trim().length()==0)
        {
            if (VERBOSE)
                System.out.println("	start to find pbo process!");
            Persistable p = (Persistable) pbo;
            NmOid nmoid = NmOid.newNmOid(PersistenceHelper.getObjectIdentifier(p));
            QueryResult qr = NmWorkflowHelper.service.getRoutingHistoryData(nmoid);
            while (qr.hasMoreElements())
            {
                process = (WfProcess) qr.nextElement();
                //判断wfRequester,如果wfRequester不为空,且类型为WfRequesterActivity那么process就是子流程
                WfRequester wfRequester = process.getRequester();
                if (wfRequester != null && (wfRequester instanceof WfRequesterActivity))
                    continue;
                else
                {
                    if (VERBOSE)
                        System.out.println("	find pbo process : " + process);
                    break;
                }
            }
        }
        else
        {
            process = (WfProcess) rf.getReference(processOid).getObject();
        }

        if (process == null)
            return signatureInfo;
        else
        {
            QueryResult allWfActivities = getWfAssignedActivityByParent(process);
            while (allWfActivities.hasMoreElements())
            {
                Hashtable singleActivitySignatureInfo = new Hashtable();
                WfAssignedActivity wfAssignedActivity = (WfAssignedActivity) allWfActivities.nextElement();                                  
                if(wfAssignedActivity.getName().equals("修改")){
                	if(wfAssignedActivity.getEndTime()!=null||wfAssignedActivity.getEndTime().equals("")){                		
                		modifiedTime=wfAssignedActivity.getEndTime();
                	}
                }                
                QueryResult allWorkItems = getWorkItemByParent(wfAssignedActivity);
                while (allWorkItems.hasMoreElements())
                {
                    WorkItem workItem = (WorkItem) allWorkItems.nextElement();                               
                    String userId = workItem.getCompletedBy();
                    if (userId == null)
                        continue;                                   
                    Timestamp signatureTS = workItem.getModifyTimestamp();                                                   
                    //由于返回的workItem是把最新完成的放在前面,所以先放到singleActivitySignatureInfo中的信息是正确的
                    if (singleActivitySignatureInfo.get(userId) == null)
                    {
                        singleActivitySignatureInfo.put(userId, signatureTS);
                    }
                    else
                    {
                        continue;
                    }
                    
                }               
                signatureInfo.put(wfAssignedActivity.getName(), singleActivitySignatureInfo);
            }
        }
        //去除workItem修改时间小于任务完成时间的workItem
        if(signatureInfo.size()>0&&modifiedTime!=null){
        	Enumeration eration=signatureInfo.keys();
        	while(eration.hasMoreElements()){
        		String key=(String)eration.nextElement();
        		Hashtable hashtable=(Hashtable)signatureInfo.get(key);
        		for(int i=0;i<hashtable.size();i++){
        			Enumeration eeration=hashtable.keys();
        			while(eeration.hasMoreElements()){
        				String key1=(String)eeration.nextElement();
        				 Timestamp time=(Timestamp)hashtable.get(key1);
        				 if(modifiedTime.compareTo(time)>0&&!key.equals("编制")){
       	                     hashtable.remove(key1);
        	              }
        			}
        		}
        	}
        	
        }
        
        return signatureInfo;
    }

    /**
     *根据流程查询所有的活动
     */
    public static QueryResult getWfAssignedActivityByParent(WfProcess process) throws Exception
    {
        QuerySpec querysearch = null;
        QueryResult queryresult = null;
        querysearch = new QuerySpec(WfAssignedActivity.class);
        SearchCondition sc = new SearchCondition(WfActivity.class, "parentProcessRef.key", SearchCondition.EQUAL, PersistenceHelper.getObjectIdentifier(process));
        querysearch.appendWhere(sc);
        queryresult = PersistenceHelper.manager.find(querysearch);
        return queryresult;
    }

    /**
     *根据活动查询workItem,安已完成时间排序,最新的在前面
     */
    public static QueryResult getWorkItemByParent(WfAssignedActivity wfAssignedActivity) throws Exception
    {
        QueryResult queryresult = null;
        QuerySpec queryspec = new QuerySpec();
        queryspec = new QuerySpec(wt.workflow.work.WorkItem.class);
        SearchCondition searchcondition = new SearchCondition(wt.workflow.work.WorkItem.class, "source.key", SearchCondition.EQUAL, PersistenceHelper.getObjectIdentifier(wfAssignedActivity));
        queryspec.appendWhere(searchcondition);
        //按修改时间排序,最新修改的在第一位
        queryspec.appendOrderBy(wt.workflow.work.WorkItem.class, "thePersistInfo.modifyStamp", true);
        queryresult = PersistenceHelper.manager.find(queryspec);
        return queryresult;
    }

    public static String getSubPageUrl(NmCommandBean nmcommandbean) throws WTException
    {
        String subPageUrl = "";
        if (!RemoteMethodServer.ServerFlag)
        {
            String method = "doGetSubPageUrl";
            try
            {
                subPageUrl = (String) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[] { NmCommandBean.class }, new Object[] { nmcommandbean });
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return subPageUrl;
        }
        else
            return doGetSubPageUrl(nmcommandbean);
    }

    public static String doGetSubPageUrl(NmCommandBean nmcommandbean) throws WTException
    {
        String subPageUrl = "";
        String activityName = "";
        String wfProcessTemplateName = "";
        Persistable persistable = nmcommandbean.getPrimaryOid().getWtRef().getObject();
        if (persistable instanceof WorkItem)
        {
            WorkItem workItem = (WorkItem) persistable;
            WfAssignedActivity wfassignedActivity = (WfAssignedActivity) workItem.getSource().getObject();
            activityName = wfassignedActivity.getName();
            WfProcess wfProcess = wfassignedActivity.getParentProcess();
            wfProcessTemplateName = wfProcess.getTemplate().getName();
            subPageUrl = getSubPageUrl(wfProcessTemplateName, activityName);
            if (VERBOSE)
            {
                System.out.println("	>>>doGetSubPageUrl	subPageUrl:" + subPageUrl);
            }
        }
        return subPageUrl;
    }

    /**
     *获取对象的路由处理记录
     * @param nmoid
     * @return
     * @throws WTException
     */
    public static QueryResult getRoutingHistoryData(NmOid nmoid) throws WTException
    {
        if (!SERVER)
        {
            try
            {
                Class aclass[] = { NmOid.class };
                Object aobj[] = { nmoid };
                return (QueryResult) RemoteMethodServer.getDefault().invoke("getRoutingHistoryData", CLASSNAME, null, aclass, aobj);
            }
            catch (InvocationTargetException invocationtargetexception)
            {
                Throwable throwable = invocationtargetexception.getTargetException();
                if (throwable instanceof WTException)
                {
                    throw (WTException) throwable;
                }
                else
                {
                    Object aobj2[] = { "getRoutingHistoryData" };
                    throw new WTException(throwable, "wt.fc.fcResource", "0", aobj2);
                }
            }
            catch (RemoteException remoteexception)
            {
                Object aobj1[] = { "getRoutingHistoryData" };
                throw new WTException(remoteexception, "wt.fc.fcResource", "0", aobj1);
            }
        }
        Object obj = null;
        WfProcess wfprocess = null;
        QueryResult queryresult = null;
        if (nmoid.isA(wt.workflow.engine.WfProcess.class))
        {
            wfprocess = (WfProcess) nmoid.getRef();
        }
        if (wfprocess != null)
        {
            obj = getPBO(wfprocess);
        }
        else
        {
            obj = (Persistable) nmoid.getRef();
        }
        if (obj != null)
        {
            queryresult = getAssociatedProcesses(((WTObject) (obj)), null, null);
        }
        else
        {
            queryresult = null;
        }
        return queryresult;
    }

    /**
     *根据流程主对象或者随签对象获取相关的流程
     * @param persistable
     * @return
     * @throws WTException
     */
    public static QueryResult getAssociatedProcesses(WTObject persistable) throws WTException
    {
        if (!SERVER)
        {
            try
            {
                Class aclass[] = { WTObject.class };
                Object aobj[] = { persistable };
                return (QueryResult) RemoteMethodServer.getDefault().invoke("getAssociatedProcesses", CLASSNAME, null, aclass, aobj);
            }
            catch (InvocationTargetException invocationtargetexception)
            {
                Throwable throwable = invocationtargetexception.getTargetException();
                if (throwable instanceof WTException)
                {
                    throw (WTException) throwable;
                }
                else
                {
                    Object aobj2[] = { "getAssociatedProcesses" };
                    throw new WTException(throwable, "wt.fc.fcResource", "0", aobj2);
                }
            }
            catch (RemoteException remoteexception)
            {
                Object aobj1[] = { "getAssociatedProcesses" };
                throw new WTException(remoteexception, "wt.fc.fcResource", "0", aobj1);
            }
        }
        return getAssociatedProcesses(persistable, null, null);
    }

    /**
     *根据流程主对象,流程状态,以及所在容器,获取相关的流程
     * @param persistable
     * @param wfstate
     * @param wtcontainerref
     * @return
     * @throws WTException
     */
    public static QueryResult getAssociatedProcesses(WTObject persistable, WfState wfstate, WTContainerRef wtcontainerref) throws WTException
    {
        String s = null;
        if (persistable instanceof WfExecutionObject)
        {
            return new QueryResult();
        }
        ReferenceFactory referencefactory = new ReferenceFactory();
        //CUSTOMIZATION No.1 by zita 20091101
        QueryResult returnresult = new QueryResult();
        if (persistable instanceof IBAHolder)
        {
            try
            {
                String pprooid = (String) IBAUtil.getIBAValue((IBAHolder) persistable, "ProcessInfo");
                pprooid= pprooid == null? "": pprooid;
                if (pprooid.length() > 0)
                {
                    WfProcess parentProcess = (WfProcess) referencefactory.getReference(pprooid).getObject();
                    if (parentProcess != null)
                    {
                        ObjectVector objectvector = new ObjectVector();
                        objectvector.addElement(parentProcess);
                        returnresult.append(objectvector);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new WTException(exception);
            }

        }
        //CUSTOMIZATION NO.1 by zita --- end

        s = referencefactory.getReferenceString(persistable);
        if ((persistable instanceof Workable) && WorkInProgressHelper.isWorkingCopy((Workable) persistable) && (persistable instanceof Iterated))
        {
            Iterated iterated = VersionControlHelper.service.predecessorOf((Iterated) persistable);
            String s1;
            if (iterated != null)
            {
                s1 = referencefactory.getReferenceString(iterated);
            }
        }
        QuerySpec queryspec = new QuerySpec(wt.workflow.engine.WfProcess.class);
        if (persistable instanceof Iterated)
        {
            wt.vc.Mastered mastered = ((Iterated) persistable).getMaster();
            queryspec.appendOpenParen();
            QueryResult queryresult = VersionControlHelper.service.allVersionsOf(mastered);
            String s2 = referencefactory.getReferenceString((Persistable) queryresult.nextElement());
            queryspec.appendWhere(new SearchCondition(wt.workflow.engine.WfProcess.class, "businessObjReference", "=", s2), 0);
            String s3;
            for (; queryresult.hasMoreElements(); queryspec.appendWhere(new SearchCondition(wt.workflow.engine.WfProcess.class, "businessObjReference", "=", s3), 0))
            {
                queryspec.appendOr();
                s3 = referencefactory.getReferenceString((Persistable) queryresult.nextElement());
            }

            queryspec.appendCloseParen();
        }
        else
        {
            String s4 = referencefactory.getReferenceString(persistable);
            queryspec.appendWhere(new SearchCondition(wt.workflow.engine.WfProcess.class, "businessObjReference", "=", s4), 0);
        }
        if (wfstate != null)
        {
            queryspec.appendAnd();
            queryspec.appendOpenParen();
            Enumeration enumeration = wfstate.getSubstates();
            WfState wfstate1 = (WfState) enumeration.nextElement();
            queryspec.appendWhere(new SearchCondition(wt.workflow.engine.WfProcess.class, "state", "=", wfstate1), 0);
            WfState wfstate2;
            for (; enumeration.hasMoreElements(); queryspec.appendWhere(new SearchCondition(wt.workflow.engine.WfProcess.class, "state", "=", wfstate2), 0))
            {
                queryspec.appendOr();
                wfstate2 = (WfState) enumeration.nextElement();
            }

            queryspec.appendCloseParen();
        }
        if (wtcontainerref != null)
        {
            queryspec.appendAnd();
            queryspec.appendWhere(new SearchCondition(wt.workflow.engine.WfProcess.class, "containerReference.key", "=", (ObjectIdentifier) wtcontainerref.getKey()), 0);
        }

        queryspec.appendOrderBy(wt.workflow.engine.WfProcess.class, "startTime", true);

        //CUSTOMIZATION NO.2 by zita 20091101
        QueryResult tempresult = new QueryResult();
        tempresult = PersistenceHelper.manager.find(queryspec);
        if (tempresult != null)
        {
            ObjectVector objectvector = new ObjectVector();
            do
            {
                if (!tempresult.hasMoreElements())
                {
                    break;
                }
                WfProcess each = (WfProcess) tempresult.nextElement();
                objectvector.addElement(each);
            }
            while (true);
            returnresult.append(objectvector);
        }

        //return PersistenceHelper.manager.find(queryspec);
        return returnresult;
        //CUSTOMIZATION NO.2 by zita --- end
    }

    /**
     *根据流程获取流程主对象
     * @param wfprocess
     * @return
     * @throws WTException
     */
    private static WTObject getPBO(WfProcess wfprocess) throws WTException
    {
        WTObject wtobject = null;
        ReferenceFactory referencefactory = new ReferenceFactory();
        WTReference wtreference = wfprocess.getBusinessObjectReference(referencefactory);
        if (wtreference == null && wfprocess.isNested())
        {
            wtobject = (WTObject) wfprocess.getContext().getValue("primaryBusinessObject");
        }
        if (wtreference != null && wtreference.getKey() != null)
        {
            wtobject = (WTObject) wtreference.getObject();
        }
        return wtobject;
    }

    public static String getSubPageUrl(String wfProcessTemplateName, String activityName) throws WTException
    {
        if (VERBOSE)
        {
            System.out.println("	>>>getSubPageUrl	wfProcessTemplateName:" + wfProcessTemplateName + "	activityName:" + activityName);
            System.out.println("	>>>getSubPageUrl	configFilePath:" + configFilePath);
        }

        if (configFilePath == null || configFilePath.length() == 0)
            throw new WTException("没有找到configFilePath,请确认site.xconf文件中ext.generic.WFTemplateGuide属性的配置!");
        XSSFWorkbook wb = null;
        FileInputStream fis = null;
        try
        {
            fis = new FileInputStream(configFilePath);
            wb = new XSSFWorkbook(fis);
        }
        catch (IOException ioe)
        {
            wb = null;
        }
        finally
        {
            try
            {
                fis.close();
            }
            catch (IOException ioe2)
            {
                throw new WTException("关闭配置文件出现异常!");
            }
        }
        if (wb == null)
            throw new WTException("没有找到configFilePath对应的配置文件!");
        XSSFSheet sheet = wb.getSheet(sheetName);
        if (sheet == null)
            throw new WTException("没有找到configFilePath对应的配置文件名为:" + sheetName + "的sheet!");
        Iterator rows = sheet.rowIterator();
        int rowNumber = 0;
        XSSFRow row;
        XSSFCell cell;

        int nSheetRow = sheet.getLastRowNum();

        if (VERBOSE)
        {
            System.out.println("	>>>getSubPageUrl	nSheetRow:" + nSheetRow);
        }
        //读取配置文件
        for (int i = 0; i < nSheetRow; i++)
        {
            //工作流模板名
            String s = getExcelCellContent(sheet, i, 0);
            if (VERBOSE)
            {
                System.out.println("	>>>getSubPageUrl	找到工作流模板:" + s);
            }
            if (s.equalsIgnoreCase(wfProcessTemplateName))
            {
                //活动名
                for (int j = i + 1; j < nSheetRow; j++)
                {
                    String ss = getExcelCellContent(sheet, j, 1);
                    if (VERBOSE)
                    {
                        System.out.println("	>>>getSubPageUrl	找到工作流模板:" + s + "	找到活动:" + ss);
                    }
                    //到达下一个工作流模板时跳出循环
                    if (ss == null || ss.length() == 0)
                        break;
                    else if (ss.equalsIgnoreCase(activityName))
                    {
                        rowNumber = j;
                        break;
                    }
                }
            }
            if (rowNumber != 0)
                break;
        }
        if (rowNumber == 0)
        {
            throw new WTException("配置文件中没有对工作流模板名:" + wfProcessTemplateName + " 活动名:" + activityName + " 进行配置!");
        }

        if (VERBOSE)
        {
            System.out.println("	<<<getSubPageUrl	wfProcessTemplateName:" + wfProcessTemplateName + "	activityName:" + activityName);
            System.out.println("	<<<getSubPageUrl	configFilePath:" + configFilePath);
        }

        return getExcelCellContent(sheet, rowNumber, 2);

    }

    /**
     *获取流程正在运行的流程任务节点
     */
    private static QueryResult getActiveAssignedActivity(WfProcess wfprocess) throws WTException
    {
        QuerySpec querysearch = null;
        QueryResult queryresult = null;
        querysearch = new QuerySpec(WfAssignedActivity.class);
        SearchCondition sc = new SearchCondition(WfAssignedActivity.class, "parentProcessRef.key", SearchCondition.EQUAL, getOid(wfprocess));
        querysearch.appendSearchCondition(sc);
        querysearch.appendAnd();
        SearchCondition sc2 = new SearchCondition(WfAssignedActivity.class, WfAssignedActivity.STATE, SearchCondition.EQUAL, WfState.OPEN_RUNNING);
        querysearch.appendSearchCondition(sc2);
        queryresult = PersistenceHelper.manager.find(querysearch);
        if (VERBOSE)
            System.out.println("	found " + queryresult.size() + " active assigned activities.");
        return queryresult;
    }

    /**
     *根据流程或流程主要业务对象,获取其正在运行的流程任务节点
     */
    public static QueryResult getActiveAssignedActivities(WTObject wtobject) throws WTException
    {
        if (wtobject instanceof WfProcess)
        {
            return getActiveAssignedActivity((WfProcess) wtobject);
        }
        else
        {
            QueryResult processes = WfEngineHelper.service.getAssociatedProcesses(wtobject, WfState.OPEN_RUNNING, ((WTContained) wtobject).getContainerReference());
            if (VERBOSE)
                System.out.println("	found " + processes.size() + " running workflow by PBO(" + wtobject.getIdentity() + ".");
            while (processes.hasMoreElements())
            {
                return getActiveAssignedActivity((WfProcess) processes.nextElement());
            }
        }

        return null;
    }

    /**
     *获取指定对象(流程主要业务对象或流程对象)的流程当前任务节点的参与者
     *@param wtobject 流程主要业务对象(PBO)或流程对象(WfProcess)
     */
    public static Vector getActiveAssignedActivityParticipants(WTObject wtobject) throws WTException
    {
        QueryResult activities = getActiveAssignedActivities(wtobject);
        if (activities == null || activities.size() <= 0)
            return null;
        Vector participants = new Vector();
        while (activities.hasMoreElements())
        {
            WfAssignedActivity activity = (WfAssignedActivity) activities.nextElement();
            Vector principals = WorkflowHelper.service.getAssignees(activity);
            for (int i = 0; i < principals.size(); i++)
            {
                Object principal = principals.elementAt(i);
                if (principal instanceof WTPrincipalReference)
                    principal = ((WTPrincipalReference) principal).getPrincipal();
                if (!participants.contains(principal))
                    participants.add(principal);
            }
        }
        if (VERBOSE)
            System.out.println("	found " + participants.size() + " participants.");
        return participants;
    }

    private static ObjectIdentifier getOid(Object obj)
    {
        if (obj == null)
        {
            return null;
        }
        if (obj instanceof ObjectReference)
        {
            return (ObjectIdentifier) ((ObjectReference) obj).getKey();
        }
        else
        {
            return PersistenceHelper.getObjectIdentifier((Persistable) obj);
        }
    }

    /*
     * 设置所有ECA状态为实施
     */

    public static void setECAStates(WTObject pbo, String states) throws WTException
    {
        if (pbo instanceof WTChangeOrder2)
        {
            WTChangeOrder2 ecn = (WTChangeOrder2) pbo;
            QueryResult queryresult = ChangeHelper2.service.getChangeActivities(ecn);
            while (queryresult.hasMoreElements())
            {
                WTChangeActivity2 ca = (WTChangeActivity2) queryresult.nextElement();
                LifeCycleHelper.service.setLifeCycleState(ca, State.toState(states));
            }
        }
    }

    /*
    * 设置ECA产生的对象的状态
    */

    public static void setChangeablesAfterStates(WTObject pbo, String states) throws WTException
    {
        if (pbo instanceof WTChangeOrder2)
        {
            WTChangeOrder2 ecn = (WTChangeOrder2) pbo;
            QueryResult qr = ChangeHelper2.service.getChangeablesAfter(ecn);
            if (qr == null || qr.size() <= 0)
                return;
            while (qr.hasMoreElements())
            {
                LifeCycleManaged lcm = (LifeCycleManaged) qr.nextElement();
                LifeCycleHelper.service.setLifeCycleState(lcm, State.toState(states));
            }
        }
    }

    /**
     *获取Excel(2007）中指定表格中的内容
     * @param sheet
     * @param nRow
     * @param nCol
     * @return
     */
    public static String getExcelCellContent(XSSFSheet sheet, int nRow, int nCol)
    {
        if (sheet == null || nRow < 0 || nCol < 0)
            return "";
        try
        {
            XSSFRow row = sheet.getRow(nRow);
            if (row == null)
                return "";
            XSSFCell aCell = row.getCell(nCol);
            if (aCell == null)
                return "";
            String content = aCell.getStringCellValue();
            if (content != null)
                content = content.trim();
            if (content == null)
                content = "";
            return content;
        }
        catch (Exception e)
        {
            System.out.println("    getExcelCellContent : error, nRow = '" + nRow + "' , nCol = '" + nCol + "'");
            e.printStackTrace();
        }
        return "";
    }
    public static WTArrayList checkReviewObjectsForSubmitForJSTZD(WTArrayList reviewObjects) throws WTException,PropertyVetoException,RemoteException
    {
    	Locale locale = SessionHelper.manager.getLocale();
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".checkReviewObjectsForSubmit2()");
        StringWriter errBuf = new StringWriter();
        PrintWriter pw = new PrintWriter(errBuf);
        Hashtable errParts = new Hashtable();
        Hashtable checkedObjects = new Hashtable();
        for (int i = 0; i < reviewObjects.size(); i++)
        {
            WTObject wtobject = (WTObject) reviewObjects.getPersistable(i);
            wtobject = (WTObject) PersistenceHelper.manager.refresh(wtobject);
            if (checkedObjects.get(wtobject.toString()) != null)
                continue;
            else
            {
                checkedObjects.put(wtobject.toString(), wtobject);
            }

            // 对于不是最新小版本的对象，获取其最新小版本，然后检查其是否检出；如果是检出，则记录在错误信息缓存中；
            if (!((Iterated) wtobject).isLatestIteration())
            {
                WTObject iterated = (WTObject) VersionControlHelper.service.getLatestIteration((Iterated) wtobject, false);
                if (ext.com.workflow.WorkflowUtil.isObjectCheckedOut(iterated))
                {
                    pw.println("随签的对象 " + iterated.getDisplayIdentity() + " 被检出.");
                }
                else
                {
                    reviewObjects.remove(wtobject);
                    reviewObjects.add(iterated);
                    wtobject = iterated;
                }
            }
            // 对于是最新小版本的对象，检查其是否检出；如果是检出，则记录在错误信息缓存中；
            else
            {
                if (ext.com.workflow.WorkflowUtil.isObjectCheckedOut(wtobject))
                {
                    pw.println("随签的对象 " + wtobject.getDisplayIdentity() + " 被检出.");
                }
            }
            if(wtobject instanceof WTDocument)
            {
            	WTDocument doc=(WTDocument)wtobject;
            	Hashtable ibas=IBAUtil.getIBAValues(doc);
            	String smalltype="";
            	if(ibas!=null)
            	{
            		String ibaconfig = PdfReadExcelGuidUtil.getPropertiesValue(PROEPETIESFILE, "wf.doc.smallType");
            		smalltype = (String) ibas.get(ibaconfig);
            	}
        		String docType = ClientTypedUtility.getLocalizedTypeName(doc, locale);
                if(docType.equals("技术通知单"))   
                {
                	boolean contain=isContainDWG(doc);
                	if(contain)
                	{
                		if(smalltype==null||!smalltype.equals("有图"))
                            pw.println("随签的对象 " + wtobject.getDisplayIdentity() + " 附件中有DWG文件，其文档小类属性必须是“有图”");

                	} 
                	if(smalltype!=null||!smalltype.equals("有图"))
                	{
                		if(!contain)
                            pw.println("随签的对象 " + wtobject.getDisplayIdentity() + " 文档小类属性是“有图”,附件中必须有DWG文件");
                	}
                }
            }
        }
        pw.flush();
        if (errBuf.toString().length() > 0)
        {
            throw new WTException(errBuf.toString());
        }
        return reviewObjects;
    }
        public static boolean isContainDWG(WTDocument doc) throws WTException, PropertyVetoException
        {
        	boolean contain=false;
            	ContentHolder docholder = ContentHelper.service.getContents((ContentHolder) doc);
        		Vector apps = ContentHelper.getContentList(docholder);
        		Enumeration e = apps.elements();
        		while (e.hasMoreElements())
        		{
        			ContentItem contentItem = (ContentItem) e.nextElement();
        			if (contentItem.getRole().equals(ContentRoleType.SECONDARY))
        			{
        				if (contentItem instanceof ApplicationData)
        				{
        					String appname = ((ApplicationData) contentItem).getFileName();
        					if(appname.toUpperCase().endsWith(".DWG"));
        						contain=true;
        				}
        			}
        		}
            return contain;
        }

        //进阶料号生效地维护验证
	public static void getpartNumberEffectiveSiteByPart(WTObject object) throws WTException, RemoteException {
		WTPart part = null;
		System.out.println("====>>>object<<===="+object.getClass());
			if (object instanceof WTPart) {
				System.out.println("====>>>start  into <<====");
				part = (WTPart) object;
				List<String> effectiveSite = IbaAttributeUtil.getAttributeValues(part, "partNumberEffectiveSite");
				System.out.println("进阶提交料号生效地1======>>>>"+effectiveSite.isEmpty());
				System.out.println("进阶提交料号生效地2======>>>>"+effectiveSite.size());
				System.out.println();
				if (TMTypeUtil.isSemiFinishedGood(part)) {
					if (effectiveSite.isEmpty()) {
						throw new WTException("料号生效地为空，请维护！");
					} else if (effectiveSite.size() > 1) {
						throw new WTException("进阶物料料号生效地未维护，只能为单值！");
					}
				}else {
					if (effectiveSite.isEmpty()) {
						throw new WTException("料号生效地为空，请维护！");
					} 
				}
//				if("".equals(partNumberEffectiveSite)||!partNumberEffectiveSite.isEmpty()||partNumberEffectiveSite.equals(" ")) {
//					
//				}
			}
	}
	
	/***
	 * 判断当前图纸是否为偏光片类型的受控图纸
	 * @param object
	 * @throws WTException 
	 * @throws RemoteException 
	 */
	public static boolean getPartNumberByDraw(WTObject object) throws RemoteException, WTException {
		System.out.println("======start 判断当前图纸是否为偏光片类型的受控图纸======");
		boolean bean = false;
		WTDocument document = null;
		String partNumber = "";
		
		if (object instanceof WTDocument) {
			document = (WTDocument)object;
			partNumber =((String)IBAUtil.getIBAValue(document, "Item")).trim();
			Vector partNumberEffectiveSite = IBAUtil.getIBAValue2(document, "moduleOrigin");
			System.out.println("partNumber=======>>"+partNumber);
			System.out.println("partNumberEffectiveSite1=======>>"+partNumberEffectiveSite);
			if (partNumberEffectiveSite.contains("厦门G5.5") || partNumberEffectiveSite.contains("厦门G6")) {

				if (partNumber.startsWith("104")) {
					bean = true;
				}
			}
			
		}
		return bean;
	}
	
	
	public static void getPartEffectiveSite(WTObject obj) {
		System.out.println("======start 判断进阶物料是否包含多个料号生效地======");
		if (obj instanceof WTPart) {
			
		}
	}
	
	
}
